package com.teamb6.shop.controller.front;


import com.github.pagehelper.Page;
import com.teamb6.shop.domain.*;
import com.teamb6.shop.domain.Collection;
import com.teamb6.shop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
public class FrontGoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CateService cateService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private  CollectionService collectionService;



    @GetMapping("/detail")
    public String detailGoods(Integer goodsid, Model model){

        //要传回的数据存在HashMap中
        Map<String,Object> goodsInfo = new HashMap<>();

        //要查询商品的基本信息
        Goods good = goodsService.selectById(goodsid);

        //查询商品的类别(根据商品表中的分类号)
        Category category = cateService.findCategoryByPrimaryKey(good.getCategory());

        //商品图片
        List<ImagePath> imagePaths = goodsService.findImagePath(goodsid);

        //商品折扣信息
        Activity activity = activityService.findActivity(good.getActivityid());
        good.setActivity(activity);
        Float disprice = good.getPrice()*activity.getDiscount()/10;
        good.setDisprice(disprice);

        //返回到详情页面的数据
        goodsInfo.put("good",good);
        goodsInfo.put("category",category);
        goodsInfo.put("imagePaths",imagePaths);
        model.addAttribute("goodsInfo",goodsInfo);

        //下拉框
        List<Category> categoryList=cateService.listCategoryAndGoodNumber();
        model.addAttribute("categoryList",categoryList);

        //评论信息
        CommentExample commentExample=new CommentExample();
        commentExample.or().andGoodsidEqualTo(good.getGoodsid());
        List<Comment> commentList=commentService.selectByExample(commentExample);

        for (Integer i=0;i<commentList.size();i++)
        {
            Comment comment=commentList.get(i);
            User commentUser=userService.findUserByPrimaryKey(comment.getUserid());
            comment.setPicPath(commentUser.getPicpath());
            comment.setUsername(commentUser.getUsername());

            commentList.set(i,comment);
        }
        model.addAttribute("commentList",commentList);


        return "deal_single";
    }


    //根据分类id查找商品
    @RequestMapping("/getByCateId")
    public String getByCategoryId(Integer categoryId, Model model, Integer pageNum, Integer pageSize, Integer pageIndex, HttpServletRequest request){
        User user= (User) request.getSession().getAttribute("user");
        if (pageSize==null){
            pageSize=6;
        }
        if (pageNum==null){
            pageNum=1;
        }
        if (pageIndex == null){
            pageIndex =1;
        }

        List<Goods> goodsList = goodsService.getByCategoryId(categoryId,pageNum,pageSize);
        int total = (int) ((Page) goodsList).getTotal();
        int num = total%pageSize == 0? total/pageSize:total/pageSize+1;
        int pages[] = new int[num];
        for(int i =0;i<num;i++){
            pages[i]=i+1;
        }

        List<Category> categoryList=cateService.listCategoryAndGoodNumber();
        model.addAttribute("categoryList",categoryList);
        model.addAttribute("categoryId",categoryId);
        model.addAttribute("goodsList",setGoodsListCollection(goodsList,user));
        model.addAttribute("pages",pages);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("pageIndex",pageIndex);
        return "goods-by-category";
    }

    //判断当前商品是否被当前用户收藏
    public Goods setGoodsCollection(Goods goods, User user){
        if(user==null) {
            goods.setCollection(false);
        }else {
            Collection collection=collectionService.getByCollectionKey(user.getUserid(),goods.getGoodsid());//
            if(collection==null) {
                goods.setCollection(false);
            }else {
                goods.setCollection(true);
            }
        }
        return goods;
    }
    //判断商品List中所有商品是否被当前用户收藏
    public List<Goods> setGoodsListCollection(List<Goods> goodsList, User user){
        for (Goods goods:goodsList
        ) {
            setGoodsCollection(goods,user);

        }
        return goodsList;
    }

    //搜索框-联想查询（ajax请求输入字段不断查询数据库）
    @GetMapping("/searchGoodsName")
    @ResponseBody
    public List<Goods> searchGoodsName(@RequestParam("parameter") String parameter){
        parameter = "%"+parameter+"%";
        GoodsExample example = new GoodsExample();
        example.or().andGoodsnameLike(parameter);
        List<Goods> goodsList = goodsService.selectByExample(example);
        return goodsList;
    }

    //每天更新商品的数量
    @PostMapping("/getUpdateCount")
    @ResponseBody
    public List<Goods> getUpdateCount(@RequestParam("uptime") String uptimae){
        Long time = System.currentTimeMillis(); //当天的时间戳
        long zero = time/(1000*3600*24)*(1000*3600*24) - TimeZone.getDefault().getRawOffset();//当天开始的时间戳
        Date zerotime = new Date(zero);

        Calendar calendar2 = Calendar.getInstance();

        calendar2.set(calendar2.get(Calendar.YEAR), calendar2.get(Calendar.MONTH), calendar2.get(Calendar.DAY_OF_MONTH),
                23, 59, 59);
        Date endtime = calendar2.getTime();

        GoodsExample example = new GoodsExample();
        example.or().andUptimeBetween(zerotime,endtime);

        List<Goods> goods= goodsService.selectByExample(example);

        //将查到的商品和图片返回
        List<Goods> goodsList = new ArrayList<>();
        for(Integer k=0;k <goods.size();k++){
            List<ImagePath> imagePathList = goodsService.findImagePath(goods.get(k).getGoodsid());
            goods.get(k).setImagePaths(imagePathList);
            goodsList.add(goods.get(k));
        }
        return goodsList;
    }



}
